package com.ml.view;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.ml.app.MyApplication;
import com.ml.tools.BaseActivity;
import com.ml.tools.Utils;

import org.json.JSONArray;
import org.json.JSONObject;

public class MainActivity2 extends BaseActivity {
    // SimpleDateFormat df1 = new SimpleDateFormat("HH:mm:ss");
    String shijian = "", riqi;
    float sc = 0, zsc, pph, rft;//时长
    int dqmb = 0;//当前目标
    int jpcl = 0;//一个节拍的产量
    int bad = 0, jinshu = 0, hege = 0, mmbcl = 0, dcl = 0, pph2 = 0;
    String dclstr, dqclstr, pphstr, yichangstr;
    RequestQueue mQueue = null;
    JsonObjectRequest mJsonObjectRequest = null;
    boolean fanhui = true;
    Intent intent;
    String js1 = "javascript:createChart(0,'" + dqclstr + "',600);", js2 = "javascript:createChart(0,'" + dclstr + "');", js3 = "javascript:createChart(0,'" + pphstr + "',12);";
    boolean b = true;
    boolean _isgetting = false;
    private WebView web1;
    private WebView web2;
    private WebView web3;
    private String chanxian, sn, renshu, k1, k2, k3, j1, j2, j3, mbcl, po, jiepai, taitou, mbpph;
    private TextView tmbcl;
    private TextView tpo;
    private TextView tline;
    private TextView trenshu;
    private TextView tmbpph;
    private TextView tdqmb;
    private TextView tsc;
    private TextView trft;
    private TextView tdqcl;
    private TextView ttime;
    private TextView ttitle;
    private TextView ttishi;
    @SuppressLint("ResourceAsColor")
    Handler mHander = new Handler() {
        public void handleMessage(Message msg) {
            try {
                switch (msg.what) {
                    case 0: {
                        JSONObject json = (JSONObject) msg.obj;
                        String re = json.getString("result");
                        if (re.equals("yes")) {
                            ttishi.setText("");
                            JSONArray array = json.optJSONArray("data");
                            if (array != null) {
                                JSONObject obj = array.optJSONObject(0);
                                if (obj != null) {
                                    hege = obj.optInt("hege");
                                    bad = obj.optInt("bad");
                                    jinshu = obj.optInt("jinshu");
                                    po = obj.optString("po");
                                    shijian = obj.optString("time");
                                    ttime.setText(shijian);
                                    sc = cha(shijian);
                                    tsc.setText(String.format("%.2f", sc));
                                    dqmb = ((int) sc + 1) * jpcl;
                                    tdqmb.setText(dqmb + "");
                                    dcl = hege * 100 / dqmb;
                                    pph = hege / sc / Integer.parseInt(renshu);
                                    String sw = String.format("%.2f", pph);
                                    sw = sw.replace(",", ".");
                                    pph = Float.parseFloat(sw);
                                    tpo.setText(po);
                                    rft = (hege - bad - jinshu) / (float) hege * 100;
                                    if (rft <= 0)
                                        rft = 0;
                                    if (rft < 95)
                                        trft.setTextColor(android.graphics.Color.RED);
                                    else
                                        trft.setTextColor(android.graphics.Color.rgb(255, 165, 0));
                                    trft.setText(String.format("%.2f", rft) + "%");
                                    if (hege < dqmb * 95 / 100)
                                        tdqcl.setTextColor(android.graphics.Color.RED);
                                    else
                                        tdqcl.setTextColor(android.graphics.Color.rgb(255, 165, 0));
                                    tdqcl.setText(hege + "");
                                }
                                js1 = "javascript:createChart(" + hege + ",'" + dqclstr + "'," + mmbcl + ");";
                                js2 = "javascript:createChart(" + dcl + ",'" + dclstr + "');";
                                js3 = "javascript:createChart(" + pph + ",'" + pphstr + "'," + pph2 + ");";
                                web1.loadUrl(js1);
                                // web1.reload();//.loadUrl();
                                web2.loadUrl(js2);
                                web3.loadUrl(js3);

                                ttitle.setText(taitou);
                                ttitle.setFocusable(true);
                            }
                        } else {

                            ttishi.setText(yichangstr);
                        }
                    }
                    break;
                    case 1:
                        if (intent == null)
                            intent = new Intent(MainActivity2.this, MyPaizhao.class);
                        intent.putExtra("taitou", taitou);
                        intent.putExtra("riqi", riqi);
                        startActivity(intent);
                        break;
                }

            } catch (Exception e) {
                ttishi.setText(yichangstr);
            }
        }
    };
    private final String url = MyApplication.SERVERPATH + "/Y502/TvgetData";//sn
    private TextView ttline;
    private TextView ttpo;
    private TextView ttmbcl;
    private TextView ttrenshu;
    private TextView ttmbpph;
    private TextView ttdqmb;
    private TextView ttsc;
    private TextView ttdqcl;
    private long firstTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main2);
        chanxian = getIntent().getStringExtra("linename");
        sn = getIntent().getStringExtra("sn");
        renshu = getIntent().getStringExtra("renshu");
        k1 = getIntent().getStringExtra("k1");
        k2 = getIntent().getStringExtra("k2");
        k3 = getIntent().getStringExtra("k3");
        j1 = getIntent().getStringExtra("j1");
        j2 = getIntent().getStringExtra("j2");
        j3 = getIntent().getStringExtra("j3");
        mbcl = getIntent().getStringExtra("mbcl");
        mmbcl = Integer.parseInt(mbcl);
        mbpph = getIntent().getStringExtra("mbpph");
        pph2 = (int) (2 * Float.parseFloat(mbpph));
//		pph2=2*Integer.parseInt(mbpph);
        jiepai = getIntent().getStringExtra("jiepai");
        taitou = getIntent().getStringExtra("taitou");
        po = getIntent().getStringExtra("po");
        riqi = getIntent().getStringExtra("riqi");
        yichangstr = MyApplication.map.get("yichang");
        pphstr = MyApplication.map.get("npph");
        dclstr = MyApplication.map.get("dcl");
        dqclstr = MyApplication.map.get("dqcl");
        shijian = "00:00:01";
        zsc = zcha();
        if (zsc < 0.1)
            zsc = (float) 0.1;
        jpcl = (int) (Integer.parseInt(mbcl) * Integer.parseInt(jiepai) / 60 / zsc);
        if (jpcl < 1) {
            jpcl = 1;
        }
        mQueue = MyApplication.getRequestQueue();
        setView();
    }

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onRestart() {

        super.onStart();
    }

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onResume() {
        b = true;
        new MyThread().start();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        b = false;
        super.onDestroy();

        reset();
    }

    private void getData() {
        if (_isgetting) {
            return;
        }
        boolean isConnected = Utils.toastIsNetworkConnected(this);
        if (isConnected) {
            //showProgressBar();
            _isgetting = true;
            String uu = url + "?sn=" + sn;
            mJsonObjectRequest = new JsonObjectRequest(Request.Method.POST, uu,
                    null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    //hideProgressBar();
                    parseData(response);
                    _isgetting = false;
                }


            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //hideProgressBar();
                    _isgetting = false;
                    showToast(MyApplication.map.get("network_error_try_again"));
                }
            }
            );
            mQueue.add(mJsonObjectRequest);
        } else {

            showToast(MyApplication.map.get("network_error_try_again"));
            return;
        }
    }

    protected void parseData(JSONObject response) {

        Message msg = new Message();
        msg = mHander.obtainMessage();
        msg.obj = response;
        msg.what = 0;
        mHander.sendMessage(msg);
    }

    private void setView() {
        web1 = (WebView) findViewById(R.id.main_web1);
        web2 = (WebView) findViewById(R.id.main_web2);
        web3 = (WebView) findViewById(R.id.main_web3);
        tline = (TextView) findViewById(R.id.main_line);
        tline.setText(chanxian);
        ttline = (TextView) findViewById(R.id.main_linestr);
        ttline.setText(MyApplication.map.get("productlinename"));
        tpo = (TextView) findViewById(R.id.main_po);
        tpo.setText(po);
        ttpo = (TextView) findViewById(R.id.main_postr);
        ttpo.setText(MyApplication.map.get("po"));
        tmbcl = (TextView) findViewById(R.id.main_mbcl);
        tmbcl.setText(mbcl);
        ttmbcl = (TextView) findViewById(R.id.main_mbclstr);
        ttmbcl.setText(MyApplication.map.get("todaytag"));
        trenshu = (TextView) findViewById(R.id.main_renshu);
        trenshu.setText(renshu);
        ttrenshu = (TextView) findViewById(R.id.main_renshustr);
        ttrenshu.setText(MyApplication.map.get("people_num"));
        tmbpph = (TextView) findViewById(R.id.main_mbpph);
        tmbpph.setText(mbpph);
        ttmbpph = (TextView) findViewById(R.id.main_mbpphstr);
        ttmbpph.setText(MyApplication.map.get("tagpph"));
        tdqmb = (TextView) findViewById(R.id.main_dqmb);
        ttdqmb = (TextView) findViewById(R.id.main_dqmbstr);
        ttdqmb.setText(MyApplication.map.get("todaytag1"));
        tsc = (TextView) findViewById(R.id.main_sc);
        ttsc = (TextView) findViewById(R.id.main_scstr);
        ttsc.setText(MyApplication.map.get("shichang"));
        trft = (TextView) findViewById(R.id.main_rft);
        ttdqcl = (TextView) findViewById(R.id.main_hegestr);
        ttdqcl.setText(MyApplication.map.get("dqcl"));
        tdqcl = (TextView) findViewById(R.id.main_hege);
        ttime = (TextView) findViewById(R.id.main2_time);
        ttime.setText(shijian);
        ttitle = (TextView) findViewById(R.id.main2_title);
        ttitle.setText(taitou);
        ttishi = (TextView) findViewById(R.id.main2_tishi);
        web1.getSettings().setAllowFileAccess(true);
        web1.getSettings().setJavaScriptEnabled(true);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        //tline.setText(screenWidth+":"+screenHeight);
        if (screenWidth == 1280)
            web1.loadUrl("file:///android_asset/echart/index11.html");
        else if (screenWidth == 1920)
            web1.loadUrl("file:///android_asset/echart/index.html");
        else
            web1.loadUrl("file:///android_asset/echart/index1.html");
        web1.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            public void onPageFinished(WebView view, String url) {
                //最好在这里调用js代码 以免网页未加载完成
                //web1.loadUrl(js1);
            }
        });
        web2.getSettings().setAllowFileAccess(true);
        web2.getSettings().setJavaScriptEnabled(true);

        if (screenWidth == 1280)
            web2.loadUrl("file:///android_asset/echart/index33.html");
        else if (screenWidth == 1920)
            web2.loadUrl("file:///android_asset/echart/index3.html");
        else
            web2.loadUrl("file:///android_asset/echart/index333.html");
        web2.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            public void onPageFinished(WebView view, String url) {
                //最好在这里调用js代码 以免网页未加载完成
                //web2.loadUrl(js2);
            }
        });
        web3.getSettings().setAllowFileAccess(true);
        web3.getSettings().setJavaScriptEnabled(true);
        if (screenWidth == 1280)
            web3.loadUrl("file:///android_asset/echart/index11.html");
        else if (screenWidth == 1920)
            web3.loadUrl("file:///android_asset/echart/index.html");
        else
            web3.loadUrl("file:///android_asset/echart/index1.html");
        web3.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            public void onPageFinished(WebView view, String url) {
                //最好在这里调用js代码 以免网页未加载完成
                //web3.loadUrl(js3);
            }
        });
    }


    private float cha(String sj) {
        float f = 0;
        if (k1.equals("00:00"))
            f = Float.parseFloat(sj.substring(0, 2)) - 7 + Float.parseFloat(sj.substring(3, 5)) / 60;
        if (sj.compareTo(k1) <= 0)
            f = (float) 0.1;
        if (sj.compareTo(k1) > 0 && sj.compareTo(j1) <= 0)
            f = Float.parseFloat(sj.substring(0, 2)) - Float.parseFloat(k1.substring(0, 2)) + (Float.parseFloat(sj.substring(3, 5)) - Float.parseFloat(k1.substring(3, 5))) / 60;
        if (sj.compareTo(j1) > 0 && sj.compareTo(k2) <= 0)
            f = Float.parseFloat(j1.substring(0, 2)) - Float.parseFloat(k1.substring(0, 2)) + (Float.parseFloat(j1.substring(3, 5)) - Float.parseFloat(k1.substring(3, 5))) / 60;
        if (sj.compareTo(k2) > 0 && sj.compareTo(j2) <= 0) {
            f = Float.parseFloat(j1.substring(0, 2)) - Float.parseFloat(k1.substring(0, 2)) + (Float.parseFloat(j1.substring(3, 5)) - Float.parseFloat(k1.substring(3, 5))) / 60;
            f = f + Float.parseFloat(sj.substring(0, 2)) - Float.parseFloat(k2.substring(0, 2)) + (Float.parseFloat(sj.substring(3, 5)) - Float.parseFloat(k2.substring(3, 5))) / 60;
        }
        if (sj.compareTo(j2) > 0 && sj.compareTo(k3) <= 0) {
            f = Float.parseFloat(j1.substring(0, 2)) - Float.parseFloat(k1.substring(0, 2)) + (Float.parseFloat(j1.substring(3, 5)) - Float.parseFloat(k1.substring(3, 5))) / 60;
            f = f + Float.parseFloat(j2.substring(0, 2)) - Float.parseFloat(k2.substring(0, 2)) + (Float.parseFloat(j2.substring(3, 5)) - Float.parseFloat(k2.substring(3, 5))) / 60;

        }
        if (sj.compareTo(k3) > 0 && sj.compareTo(j3) <= 0) {
            f = Float.parseFloat(j1.substring(0, 2)) - Float.parseFloat(k1.substring(0, 2)) + (Float.parseFloat(j1.substring(3, 5)) - Float.parseFloat(k1.substring(3, 5))) / 60;
            f = f + Float.parseFloat(j2.substring(0, 2)) - Float.parseFloat(k2.substring(0, 2)) + (Float.parseFloat(j2.substring(3, 5)) - Float.parseFloat(k2.substring(3, 5))) / 60;
            f = f + Float.parseFloat(sj.substring(0, 2)) - Float.parseFloat(k3.substring(0, 2)) + (Float.parseFloat(sj.substring(3, 5)) - Float.parseFloat(k3.substring(3, 5))) / 60;
        }
        if (sj.compareTo(j3) > 0 && !k3.equals("00:00")) {
            f = Float.parseFloat(j1.substring(0, 2)) - Float.parseFloat(k1.substring(0, 2)) + (Float.parseFloat(j1.substring(3, 5)) - Float.parseFloat(k1.substring(3, 5))) / 60;
            f = f + Float.parseFloat(j2.substring(0, 2)) - Float.parseFloat(k2.substring(0, 2)) + (Float.parseFloat(j2.substring(3, 5)) - Float.parseFloat(k2.substring(3, 5))) / 60;
            f = f + Float.parseFloat(j3.substring(0, 2)) - Float.parseFloat(k3.substring(0, 2)) + (Float.parseFloat(j3.substring(3, 5)) - Float.parseFloat(k3.substring(3, 5))) / 60;
        }
        if (sj.compareTo(j1) > 0 && k2.equals("00:00")) {
            f = Float.parseFloat(j1.substring(0, 2)) - Float.parseFloat(k1.substring(0, 2)) + (Float.parseFloat(j1.substring(3, 5)) - Float.parseFloat(k1.substring(3, 5))) / 60;
        }
        if (sj.compareTo(j2) > 0 && k3.equals("00:00")) {
            f = Float.parseFloat(j1.substring(0, 2)) - Float.parseFloat(k1.substring(0, 2)) + (Float.parseFloat(j1.substring(3, 5)) - Float.parseFloat(k1.substring(3, 5))) / 60;
            f = f + Float.parseFloat(j2.substring(0, 2)) - Float.parseFloat(k2.substring(0, 2)) + (Float.parseFloat(j2.substring(3, 5)) - Float.parseFloat(k2.substring(3, 5))) / 60;
        }
        return f;
    }

    private float zcha() {
        float f = 8;
        //String sj=df1.format(new Date()).substring(0, 5);
        if (k1.equals("00:00"))
            f = 8;
        else if (k2.equals("00:00")) {
            f = Float.parseFloat(j1.substring(0, 2)) - Float.parseFloat(k1.substring(0, 2)) + (Float.parseFloat(j1.substring(3, 5)) - Float.parseFloat(k1.substring(3, 5))) / 60;
        } else if (k3.equals("00:00")) {
            f = Float.parseFloat(j1.substring(0, 2)) - Float.parseFloat(k1.substring(0, 2)) + (Float.parseFloat(j1.substring(3, 5)) - Float.parseFloat(k1.substring(3, 5))) / 60;
            f = f + Float.parseFloat(j2.substring(0, 2)) - Float.parseFloat(k2.substring(0, 2)) + (Float.parseFloat(j2.substring(3, 5)) - Float.parseFloat(k2.substring(3, 5))) / 60;
        } else {
            f = Float.parseFloat(j1.substring(0, 2)) - Float.parseFloat(k1.substring(0, 2)) + (Float.parseFloat(j1.substring(3, 5)) - Float.parseFloat(k1.substring(3, 5))) / 60;
            f = f + Float.parseFloat(j2.substring(0, 2)) - Float.parseFloat(k2.substring(0, 2)) + (Float.parseFloat(j2.substring(3, 5)) - Float.parseFloat(k2.substring(3, 5))) / 60;
            f = f + Float.parseFloat(j3.substring(0, 2)) - Float.parseFloat(k3.substring(0, 2)) + (Float.parseFloat(j3.substring(3, 5)) - Float.parseFloat(k3.substring(3, 5))) / 60;
        }
        return f;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) { //如果两次按键时间间隔大于2秒，则不退出
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    firstTime = secondTime;// 更新firstTime
                    return true;
                } else { //两次按键小于2秒时，退出应用
                    b = false;
                    this.finish();
                    MyApplication.exit();
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    class MyThread extends Thread {
        int i = 0;

        @Override
        public void run() {
            getData();
            while (b) {
                try {
                    //20秒后跳转到MyPaizhao，30秒后跳回来
                    if (i == 20) {
                        b = false;
                        Message msg = new Message();
                        msg.what = 1;
                        mHander.sendMessage(msg);
                    }
                    i++;
                    Thread.sleep(1000);

//					 getData();

                } catch (InterruptedException e) {

                }
            }
        }
    }

    //重启APP
    void reset() {
        Intent intent = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//与正常页面跳转一样可传递序列化数据,在Launch页面内获得
        intent.putExtra("REBOOT","reboot");
        startActivity(intent);
//        startActivity(new Intent(this, LoginActivity.class));
    }
}
